<?php

namespace app\admin\controller\order;

use app\common\controller\Backend;
use Exception;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use app\admin\library\Auth;
use app\admin\model\personal\AccountLog;
use app\admin\model\finance\FinanceLog;
/**
 *
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{

    /**
     * Order模型对象
     * @var \app\admin\model\order\Order
     */
    protected $model = null;
    protected $goods_model = null;
    protected $personal_model = null;
    protected $noNeedRight = ['getAmount','chatlist'];
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\order\Order;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->goods_model = new \app\admin\model\goods\Goods();
        $this->personal_model = new \app\admin\model\personal\Personal();

    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $auth = Auth::instance();
            $id = $auth->id;
            //获取客服类型
            $ke_type = \app\admin\model\Admin::where(['id'=>$id])->value('type');
            //客服类型1全部2手游3端游
            if($ke_type == 2){
                //根据平台区分端游手游  手游有平台 端游无平台
                $con['order.plat_id'] = ['neq',0];
            }elseif($ke_type == 3){
                //根据平台区分端游手游  手游有平台 端游无平台
                $con['order.plat_id'] = ['eq',0];
            }else{
                $con = [];
            }
			$start_time = strtotime(date("Y-m-d"),time());
            $end_time = $start_time + 86400;

            $countAll = $this->model
                    ->where(['order_class_type'=>1,'ontime'=>['between',[$start_time,$end_time]]])
                    ->count();
            $filter = json_decode($this->request->get('filter'),true);
            if(isset($filter['overtime'])){
                $search_over_time = explode(' - ',$filter['overtime']);
                $countFinish = $this->model
                    ->where(['order_class_type'=>1,'status'=>5,'overtime'=>['between',[strtotime($search_over_time[0]),strtotime($search_over_time[1])]]])
                    ->field('count(*) as count,case when sum(amount) is null then 0 else sum(amount) end as priceAll,case when sum(price)  is null then 0 else sum(price) end as priceSall')
                    ->find();
            }else{
                $countFinish = $this->model
                    ->where(['order_class_type'=>1,'status'=>5,'overtime'=>['between',[$start_time,$end_time]]])
                    ->field('count(*) as count,case when sum(amount) is null then 0 else sum(amount) end as priceAll,case when sum(price)  is null then 0 else sum(price) end as priceSall')
                    ->find();
            }

            //查询已付款状态
            $pay_finist = $this->model->where(['order_class_type'=>1,'status'=>2])->count();

            $countCancel = $this->model
                ->where(['order_class_type'=>1,'ontime'=>['between',[$start_time,$end_time]],'status'=>['in',['7','9']]])
                ->count();
            $op['order.status'] = ['not in',[30,31]];
            $list = $this->model
                    ->with(['goods','personal','admin'])
                    ->where(['order_class_type'=>1])
                    ->where($op)
                    ->where($where)
                    ->where($con)
                    ->order($sort, $order)
		    ->field('order.id,order_class_type,goods.prices,goods.goods_sn,goods.invite as mai_invite')
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['true','fee','daifa_fee','id','order_class_type','payway', 'game_id','account','order_sn','game','plat','area','server','type_name','deposit','buy_type','invite','title','price','prices','num','amount','ontime','paytime','overtime','status','complaint','time_format','mai_invite']);
				$row->visible(['personal']);
				$row->getRelation('personal')->visible(['account','mobile']);
                $row->visible(['admin']);
				$row->getRelation('admin')->visible(['username']);
                $row->visible(['goods']);
				$row->getRelation('goods')->visible(['goods_sn']);
            }

            foreach($list as $k => $v){
                $goods = Db::name('goods')->where(['id'=>$v['goods_id']])->field('is_safe,goods_class_type,method,invite')->find();
                $goods_total_price = round($v['prices']*$v['num'],2);
                
                    $list[$k]['true'] = $goods_total_price - $v['fee'];
                
                $list[$k]['time_format']=date("Y-m-d",$v['ontime']);
				$list[$k]['title'] = mb_substr($v['title'],0,60);
                // $list[$k]['mai_invite'] = $goods['invite'];
            }
// dump($list);die;
            $result = array("total" => $list->total(),"rows" => $list->items(),"extend" => ['stat1' => $countAll, 'stat2' => $countFinish['count'],'stat3'=>$countCancel,'stat4'=>$countFinish['priceAll'],'stat5'=>round($countFinish['priceAll']-$countFinish['priceSall'],2),'stat6'=>$pay_finist]);
            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 详情
     */
    public function info($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $row['goods'] = $this->goods_model::where('id', '=', $row['goods_id'])->find();
		if($row['fee'] > 1 || $row['daifa_fee'] > 1){
            $row['act_money'] = $row['goods']['prices']*$row['num'] - $row['fee'];
        }else{
            $fee_info = $this->getAmount($row['goods']['prices']*$row['num'], $row['goods']['goods_class_type'], $row['goods']['is_safe'], $row['xyg'], $row['goods']['method'], $row['game_id'], $row['goods_type'], $row['fee'], $row['daifa_fee']);
            $row['fee'] = $fee_info['fee'];
            $row['daifa_fee']=$fee_info['daifa_fee'];

            $row['act_money']=$row['goods']['prices']*$row['num'] - $fee_info['fee'];
        }
        //$fee_info = $this->getAmount($row['goods']['prices']*$row['num'], $row['goods']['goods_class_type'], $row['goods']['is_safe'], $row['xyg'], $row['goods']['method'], $row['game_id'], $row['goods_type'], $row['fee'], $row['daifa_fee']);
        
        $row['personal'] = $this->personal_model::where('id', '=', $row['uid'])
        ->field('account,is_real,id_card,name')->find();
        $row['role_server'] = Db::name('game_info')->where('id',$row['role_server'])->value('name');
        $sku = htmlspecialchars_decode($row['goods']['sku']);

        $sku = json_decode($sku,true);
        $uid = $_SESSION['think']['admin']['id'];
        $role_id = DB::name("auth_group_access")->where('uid',$uid)->find();
		$this->view->assign('group_access',$role_id['group_id']);
        // dump($sku);
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        $this->view->assign("row", $row);
        $this->view->assign("sku", $sku);
        return $this->view->fetch();
    }


    /**
     * 客服上传截图验证
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    if($params['kf_images'] && $row['status'] == 11){
                        //如果客服已经上传截图，订单状态改为待确认
                        $params['status'] = 12;
                    }

                    //订单审核审核通过订单改为代发货。审核失败==买家原因撤单
                    // if($params['status'] == 7){
                    //     if($params['away'] == 2){
                    //         //卖家  商品下架
                    //         Db::name('goods')->where('id',$row['goods_id'])->update(['status'=>5]);
                    //     }
                    //     //商品库存退回
                    //     Db::name('goods')->where('id',$row['goods_id'])->setInc('stock',$row['num']);
                    //     //取消订单，资金退回冻结账户
                    //     $uinfo = $this->personal_model->where(['id'=>$row['buyid']])->field('balance,jy_balance')->find();
                    //     $log = new AccountLog();
                    //     $res = $log->addAccountLog($row['buyid'], '+'.$row['amount'], 5, '订单审核失败', 1,'',2);
                    //     if ($res !== false) {
                    //         Db::name('personal')->where(['id'=>$row['buyid']])->setInc( 'jy_balance', $row['amount'] );
                    //     }
                    //     $uinfo_after = $this->personal_model->where(['id'=>$row['buyid']])->field('balance,jy_balance')->find();
                    //     // dump($uinfo);
                    //     $financelog = new FinanceLog();
                    //     $financelog->addFinanceLog($row['buyid'],'订单审核失败',$uinfo['balance'],$uinfo['jy_balance'], $row['amount'], $uinfo_after['balance'],$uinfo_after['jy_balance'], '订单审核失败');
                    // }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        $this->view->assign("image", $row['kf_images']);
        return $this->view->fetch();
    }


    /**
     * 订单管控
     */
    public function manage($ids = null)
    {
        $row = $this->model->get($ids);
        $goods = Db::name('goods')->where(['id'=>$row['goods_id']])->field('is_safe,goods_class_type,method')->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
		 $guadan_list = array();
        if($row['status'] == 5 || $row['status'] == 7){
            $guadan_list = DB::name("guadan_reason")->where('order_id',$row['id'])->select();
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
					
					 if(empty($params['status'])){
                        if($row['status'] == 4){
                            $guadan_reason['admin_id']=$row['admin_id'];
                            $guadan_reason['order_id']=$row['id'];
                            $guadan_reason['admin_name'] = DB::name("admin")->where('id',$row['admin_id'])->field('nickname')->find()['nickname'];
                            $guadan_reason['created_time'] = date("Y-m-d H:i:s",time());
                            $guadan_reason['reason']=$params['reason'];
                            DB::name("guadan_reason")->insert($guadan_reason);

                            $params['status'] = $row['status'];

                        }
                    }
                    if($params['status'] == 7){
                        if($row['status'] == 7){
                            $this->error('订单已撤单');
                        }
                        //买家原因撤单 订单重新上架（即同金币一样退库存） 卖家原因撤单 商品直接下架
                        if($params['away'] == 2){
                            //卖家  商品下架
                            Db::name('goods')->where('id',$row['goods_id'])->update(['status'=>5]);
                        }
                        //商品库存退回
                        Db::name('goods')->where('id',$row['goods_id'])->setInc('stock',$row['num']);
                        //资金原路退回（微信支付宝） 余额则回退至余额
                        $id = 1988;
                        $rand = $id < 9999 ? mt_rand(100000, 99999999) : mt_rand(100, 99999);
                        $sn = date('Yhis') . $rand;
                        $id = str_pad($id, (18 - strlen($sn)), '0', STR_PAD_BOTH);
                        $refund_sn = $sn . $id;
                        if($row['payway'] == '微信'){
                            $root_path = $this->request->root(true);
                            $refund_url = str_replace('/BfcTyWlLqd.php','',$root_path).'/api/pay/notify_wechat_refund';
                            $epay = \addons\epay\library\Service::refund_wechat('0.1',$row['order_sn'],$refund_sn,'wechat','',$refund_url,'','app');
                            $params['status'] = $row['status'];
                        }else if($row['payway'] == '支付宝'){
                            $epay = \addons\epay\library\Service::refund_ali('0.1',$row['order_sn'],$refund_sn,'alipay','退款','','','app');
                            if($epay['code'] == 10000){
                                $uinfo = $this->personal_model->where(['id'=>$row['buyid']])->field('balance,jy_balance')->find();
                                $log = new AccountLog();
                                $res = $log->addAccountLog($row['buyid'], '+'.$row['amount'], 5, '后台客服撤单', 1,'',1);
                            }else{
                                $this->error("支付宝退款异常，请联系技术人员查看");
                            }
                        }else {
                            //取消订单，资金退回余额
                            $uinfo = $this->personal_model->where(['id'=>$row['buyid']])->field('balance,jy_balance')->find();
                            $log = new AccountLog();
                            $res = $log->addAccountLog($row['buyid'], '+'.$row['amount'], 5, '后台客服撤单', 1,'',1);
                            if ($res !== false) {
                                Db::name('personal')->where(['id'=>$row['buyid']])->setInc( 'balance', $row['amount'] );
                            }
                            $uinfo_after = $this->personal_model->where(['id'=>$row['buyid']])->field('balance,jy_balance')->find();
                            // dump($uinfo);
                            $financelog = new FinanceLog();
                            $financelog->addFinanceLog($row['buyid'],'订单申请撤单退回',$uinfo['balance'],$uinfo['jy_balance'], $row['amount'], $uinfo_after['balance'],$uinfo_after['jy_balance'], $params['reason']);
                        }
                    }

                    if($params['status'] == 5){
                        if($row['status'] == 5){
                            $this->error('订单已完成');
                        }
                        $params['overtime'] = time();
                        //已完成的订单给卖家到账
                        $log = new AccountLog();
                        // 心意购延迟3天
                        // 普通账号延迟打款7天。
                        // 终身包赔账号 延迟2天
                        $arrivaltime = time()+7*24*60*60;
                        $goods_total_price = round($row['price'] * $row['num'], 2);
                        $fee_info = $this->getAmount($goods_total_price, $goods['goods_class_type'], $goods['is_safe'], $row['xyg'], $goods['method'],$row['game_id'],$row['goods_type'],'','');
                        //$money = $fee_info['daifa_fee'] + $goods_total_price;
						$money = $goods_total_price - $fee_info['fee'];
			// dump($money);
                        // exit;
                        if($goods['is_safe']==1){
                            $arrivaltime = time()+2*24*60*60;
                        }
                        if($row['xyg']==2){
                            $arrivaltime = time()+3*24*60*60;
                        }
                        $log->addAccountLog($row['uid'], '+'.$money, 2, '售得', 0,$arrivaltime);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
		 $this->view->assign([
            'row'=>$row,
            'guadan_list'=>$guadan_list
            ]);
        //$this->view->assign("row", $row);
        return $this->view->fetch();
    }
    
    /**
     * 查看聊天记录
     */
    public function chat($ids = null)
    {
        $ids = $ids?$ids:$this->request->post('id');
        $row = $this->model::where('id', '=', $ids)->field('id,order_sn,uid,buyid')->find();
        $list = DB::name('timely')->where(['order_sn'=>$row['order_sn']])->select();
        if($list){
            foreach($list as $k=>$v){
                if(strpos($v['content'],'https://780g.oss-cn-zhangjiakou.aliyuncs.com') !== false){
                    //消息内容为图片
                    $list[$k]['c_type'] = 1;
                }else{
                    //消息内容为文字
                    $list[$k]['c_type'] = 2;
                }
                if($v['fromUserId']==$row['buyid']){
                    $list[$k]['title'] = '买家';
                    $list[$k]['type'] = 1;
                }else{
                    $list[$k]['title'] = '卖家';
                    $list[$k]['type'] = 2;
                }
            }
        }
        // dump($list);
        if ($this->request->isAjax()) {
            return json($list);
        }
        $this->view->assign([
                "list" => $list,
                "row" => $row,
        ]);
        return $this->view->fetch();
        
    }
    
    
    /**
     * 查看聊天记录
     */
    public function chatlist($ids = null)
    {
        $ids = $ids?$ids:$this->request->post('id');
        $row = $this->model::where('id', '=', $ids)->field('order_sn,uid,buyid')->find();
        $list = DB::name('timely')->where(['order_sn'=>$row['order_sn']])->select();
        if($list){
            foreach($list as $k=>$v){
                if(strpos($v['content'],'https://780g.oss-cn-zhangjiakou.aliyuncs.com') !== false){
                    //消息内容为图片
                    $list[$k]['c_type'] = 1;
                }else{
                    //消息内容为文字
                    $list[$k]['c_type'] = 2;
                }
                if($v['fromUserId']==$row['buyid']){
                    $list[$k]['title'] = '买家';
                    $list[$k]['type'] = 1;
                }else{
                    $list[$k]['title'] = '卖家';
                    $list[$k]['type'] = 2;
                }
            }
        }
        return json($list);
    }

    /**
     * 客服联系买/卖家
     */
    public function online($ids = null)
    {
        $row = $this->model::where('id', '=', $ids)->field('order_sn,id,uid,buyid')->find();
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /*public function getAmount($amount, $type, $safe, $xyg, $method)
    {
        $map['safe'] = $safe;
        $map['type'] = $type;
        $map['xyg'] = $xyg;
        $map['method'] = $method;
        $fee = Db::name('server')->where($map)->find();
        $aa = $amount*$fee['trade'];
        if($aa < 1){
            $amount = $amount -1;
        }else{
            if ($fee['id'] == 1) {
                $amount = $amount/(1+$fee['service'])*(1-$fee['trade']);
            } else {
                $amount = $amount*(1-$fee['trade']);
            }
        }
        return round($amount,2);
    }*/
	/**
     * @param $amount  原价
     * @param $type
     * @return array
     */
    public function getAmount($amount, $type, $safe, $xyg, $method, $game_id, $game_type, $fee_a, $daifa_fee)
    {
        $map['safe'] = $safe;
        $map['type'] = $type;
        //$map['xyg'] = $xyg;
        $map['method'] = $method;
        $map['game_id'] = $game_id;
        $map['game_type'] = $game_type;
        if (!$fee_a) {
            $fee = Db::name('server')->where($map)->find();
            if (!$fee) {
                $fee = DB::name("server")->where('id', 1)->find();
            }
            $fee_a = $fee['trade'] * $amount;
        } else {
            $fee_a = $fee_a * $amount;
        }

        if (!$daifa_fee) {
            $fee = Db::name('server')->where($map)->find();
            if (!$fee) {
                $fee = DB::name("server")->where('id', 1)->find();
            }
            $fee_b = $fee['service'] * $amount;
        } else {
            $fee_b = $daifa_fee * $amount;
        }


        return ['fee' => round($fee_a,2), 'daifa_fee' => round($fee_b,2)];
    }

}
